﻿using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class touchscreen_BuyTicket_PaymentOptions : System.Web.UI.Page
{
    //Initialize Managers
    private TicketManager ticketManager;
    private PlanningManager planningManager;
    private VoucherManager voucherManager;
    private ReservationManager reservationManager;

    //Initialize classes
    private DateTimeConverter dateTimeConverter = new DateTimeConverter();

    //Initialize variables
    private bestelling currentOrder;
    private double totalCost = 0.0;
    private double discount = 0.0;
    private planning moviePlanning;
    private film currentMovie;

    protected void Page_Load(object sender, EventArgs e)
    {
        ticketManager = new TicketManager((debioscoopEntities)Session["db"]);
        reservationManager = new ReservationManager((debioscoopEntities)Session["db"]);
        planningManager = new PlanningManager((debioscoopEntities)Session["db"]);
        voucherManager = new VoucherManager((debioscoopEntities)Session["db"]);

        //TODO: verschil reservering en bestelling
        if (Session["Bestelling"] != null)
        {
            //Get the order from the session
            currentOrder = (bestelling)Session["Bestelling"];

            //Set movie data
            movTitle.Text = currentOrder.planning.film.naam;
            movTime.Text = dateTimeConverter.getTimeforMovie(currentOrder.tijd);

            //Get planning from movie
            moviePlanning = currentOrder.planning;

            //Get every kind of ticket from the order
            List<String> ticketNames = new List<string>();
            foreach (kaartje ticket in currentOrder.kaartjes)
            {
                if (!ticketNames.Contains(ticket.abbonement.abbonementnaam))
                {
                    ticketNames.Add(ticket.abbonement.abbonementnaam);
                }
            }
            tickets.DataSource = ticketNames;
            tickets.DataBind();

            //Set price and amount of glasses if available
            if (currentOrder.brillen > 0)
            {
                amountGlasses.Text = currentOrder.brillen.ToString();
                glassesLabel.Text = "3D bril";
                int glassesPrice = 1;
                priceGlasses.Text = glassesPrice.ToString("#.00");

                //add glasses cost to totalCost
                totalCost = totalCost + (Double)(glassesPrice * currentOrder.brillen);
            }
            else
            {
                //Make glasses table row invisible
                glassesTR.Visible = false;
            }

            //Check if discount is available
            if (!priceVoucher.Text.Equals(""))
            {
                discount = double.Parse(priceVoucher.Text);
            }
            else
            {
                //Make voucher table row invisible
                voucherTR.Visible = false;
            }

            //Check if voucher is inserted
            if (!String.IsNullOrEmpty(Request.Form["voucherID"]))
            {
                int voucherID = int.Parse(Request.Form["voucherID"]);
                if (voucherManager.getVoucher(voucherID) != null)
                {
                    //Get discount from voucher and remove it from the voucher
                    discount = discount + voucherManager.getDiscount(voucherID, (totalCost - discount));
                    nameVoucher.Text = "Korting";
                    priceVoucher.Text = discount.ToString("0.00");
                    voucherTR.Visible = true;
                    lblNotification.Text = "Uw voucher is toegepast op uw bestelling!";
                }
                else
                {
                    lblNotification.Text = "Er is geen voucher gevonden met het nummer " + voucherID.ToString();
                }
            }

            //Subtract the discount (if available) from the total cost
            totalCost = totalCost - discount;

            //Set total price to the label
            total.Text = totalCost.ToString("0.00");
            currentOrder.totaal_bedrag = totalCost;

            //Set label text with active language
            voucher.Text = "Voer hier uw voucher code in voor korting";
            Master.tl.pageTranslator(payTicket.Controls);
        }
        else
        {
            Response.Redirect(Page.ResolveClientUrl("~/touchscreen/BuyTicket"));
        }
    }

    protected void tickets_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            string ticketName = e.Item.DataItem.ToString();
            int amount = currentOrder.kaartjes.Where(k => k.abbonement.abbonementnaam.Equals(ticketName)).Count();
            double price = currentOrder.planning.film.prijs;
            kaart_soort currentTicket = ticketManager.getTicketByName(ticketName);

            //Check if there is a precentage discount or fixed ammount
            if(currentTicket.kortingpercentage != 0)
            {
                price = price * ((100 - (double)currentTicket.kortingpercentage) / 100);
            }
            else
            {
                price = price - (double)currentTicket.kortingbedrag;
            }

            foreach (kaartje ticket in currentOrder.kaartjes)
            {
                if (ticket.abbonement.abbonementnaam.Equals(ticketName))
                {
                    ticket.prijs = price;
                }
            }

            //Get Labels
            Label labelTicketName = (Label)e.Item.FindControl("ticketName");
            Label labelAmount = (Label)e.Item.FindControl("amount");
            Label labelPrice = (Label)e.Item.FindControl("price");

            //Set Labels
            labelTicketName.Text = ticketName;
            labelAmount.Text = amount.ToString();
            labelPrice.Text = price.ToString("#.00");

            totalCost += amount * price;
        }
    }
    protected void pinnen_Click(object sender, ImageClickEventArgs e)
    {
        //Update or add reservation to database
        if (currentOrder.bestelling_id != 0)
        {
            reservationManager.PickupReservation(currentOrder.bestelling_id);
        }
        else
        {
            currentOrder.afgehaald = true;
            currentOrder.betaald = true;
            currentMovie = currentOrder.planning.film;
            currentOrder.planning.film = null;
            reservationManager.addReservation(currentOrder);
        }

        //create pdf for each ticket
        foreach (kaartje ticket in currentOrder.kaartjes)
        {
            OutputManager outputManager = new OutputManager("touchscreen/buyTicket/Ticket.rdlc");
            
            //set parameters for ticket
            outputManager.addParameter("movieName", currentMovie.naam);
            outputManager.addParameter("date", currentOrder.datum.ToShortDateString());
            outputManager.addParameter("time", dateTimeConverter.getTimeforMovie(currentOrder.tijd));
            outputManager.addParameter("price", ticket.prijs.ToString("0.00"));
            //outputManager.addParameter("room", ticket.zaalzaalnummer.ToString());

            String rowValue = "N/A";
            String seatValue = "N/A";

            if (currentMovie.stoelen_kiezen == true)
            {
                rowValue = ticket.rijnummer.ToString();
                seatValue = ticket.zittingnummer.ToString();
            }

            outputManager.addParameter("row", rowValue);
            outputManager.addParameter("seat", seatValue);
            
            outputManager.createTicket(Server.MapPath("~") + "\\touchscreen\\Tickets\\", ".pdf",
                currentOrder.datum.ToShortDateString() + "-" + currentOrder.bestelling_id.ToString() + "-" + ticket.kaartjeid.ToString());
        }

        if (currentOrder.brillen > 0)
        {
            OutputManager outputManager = new OutputManager("touchscreen/buyTicket/TicketBril.rdlc");
            int priceGlasses = (int)currentOrder.brillen;

            //set parameters for ticket
            outputManager.addParameter("date", currentOrder.datum.ToShortDateString());
            outputManager.addParameter("amount", currentOrder.brillen.ToString());
            outputManager.addParameter("price", priceGlasses.ToString("#.00"));

            outputManager.createTicket(Server.MapPath("~") + "\\touchscreen\\Tickets\\3DTickets\\", ".pdf", 
                currentOrder.datum.ToShortDateString() + "-" + currentOrder.bestelling_id.ToString() + "-" + "3D");
        }
        Response.Redirect("~/touchscreen");
    }
}